package com.nari.ncps.screen.service.impl.dryport;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nari.ncps.screen.entity.dryport.DryportSafetyenvLoadunload;
import com.nari.ncps.screen.mapper.dryport.DryportSafetyenvLoadunloadMapper;
import com.nari.ncps.screen.service.dryport.DryportSafetyenvLoadunloadService;
import com.nari.ncps.screen.vo.dryport.LoadUnloadVO;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.List;

/**
 * <p>
 * 装车卸车情况表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class DryportSafetyenvLoadunloadServiceImpl extends ServiceImpl<DryportSafetyenvLoadunloadMapper, DryportSafetyenvLoadunload> implements DryportSafetyenvLoadunloadService {

    @Override
    public List<LoadUnloadVO> getLoadUnloadStatistics(Integer year, Integer month, Integer day) {
        List<LoadUnloadVO> voList = new java.util.ArrayList<>();

        // 查询装车卸车数据
        QueryWrapper<DryportSafetyenvLoadunload> queryWrapper = new QueryWrapper<>();

        // 如果参数为空，使用前天的日期
        LocalDate targetDate;
        if (year == null && month == null && day == null) {
            // 没有任何参数，默认取前天
            targetDate = LocalDate.now().minusDays(2);
        } else {
            // 有参数的情况，使用当前日期填充缺失的参数
            int targetYear = (year != null) ? year : LocalDate.now().getYear();
            int targetMonth = (month != null) ? month : LocalDate.now().getMonthValue();
            int targetDay = (day != null) ? day : LocalDate.now().getDayOfMonth();
            targetDate = LocalDate.of(targetYear, targetMonth, targetDay);
        }

        // 设置查询条件
        queryWrapper.eq("year", targetDate.getYear());
        queryWrapper.eq("month", targetDate.getMonthValue());
        queryWrapper.eq("day", targetDate.getDayOfMonth());
        queryWrapper.orderByDesc("create_time")
                   .last("LIMIT 2");

        List<DryportSafetyenvLoadunload> entityList = this.list(queryWrapper);

        // 转换为VO列表
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (DryportSafetyenvLoadunload entity : entityList) {
            LoadUnloadVO vo = new LoadUnloadVO();
            vo.setLoadingStatus(entity.getLoadingStatus());
            vo.setUnloadingStatus(entity.getUnloadingStatus());
            if (entity.getDate() != null) {
                vo.setDate(sdf.format(entity.getDate()));
            }
            voList.add(vo);
        }

        return voList;
    }

}
